/**
 * 
 */
package com.puneet.graphqueries.graphs;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import partitioner.DataAccessException;
import partitioner.NodeNotFoundException;
import partitioner.PartitionDAO;

/**
 * @author puneet
 *
 */
public class MapPartitionImpl implements PartitionDAO {
	private File filename;
	private Map<String, List<String>> nodeNeighborMap = new HashMap<String, List<String>>();
	public MapPartitionImpl(String filename)throws IOException {
		this(new File(filename));
	}
	public MapPartitionImpl(File filename)throws IOException {
		this.filename = filename;
		buildMap();
	}
	/* (non-Javadoc)
	 * @see partitioner.PartitionDAO#containsNode(java.lang.String)
	 */
	@Override
	public boolean containsNode(String node) throws DataAccessException {
		return nodeNeighborMap.containsKey(node);
	}

	/* (non-Javadoc)
	 * @see partitioner.PartitionDAO#getNeighbors(java.lang.String)
	 */
	@Override
	public List<String> getNeighbors(String node) throws NodeNotFoundException, DataAccessException {
		return nodeNeighborMap.get(node);
	}

	/* (non-Javadoc)
	 * @see partitioner.PartitionDAO#getNeighborsForAllNodes(java.util.List)
	 */
	@Override
	public Map<String, List<String>> getNeighborsForAllNodes(List<String> nodes) throws NodeNotFoundException,
			DataAccessException {
		Map<String, List<String>> returnMap = new HashMap<String, List<String>>();
		for(String node:nodes) {
			returnMap.put(node, nodeNeighborMap.get(node));
		}
		return returnMap;
	}
	private void buildMap()throws IOException {
		System.out.println("Building map from file:" + this.filename);
		BufferedReader br = new BufferedReader(new FileReader(this.filename));
		String s;
		while((s=br.readLine()) != null) {
			String[] vals = s.split("\\s");
			String nodeName = vals[0];
			List<String> neighborList = new ArrayList<String>();
			for(int i=1;i<vals.length;i++) {
				neighborList.add(vals[i]);
			}
			nodeNeighborMap.put(nodeName, neighborList);
		}
	}
}
